package com.baijiayun.liveuibase.widgets.courseware;

import static com.baijiayun.liveuibase.widgets.courseware.models.TabState.CloudFile;
import static com.baijiayun.liveuibase.widgets.courseware.models.TabState.DocFile;
import static com.baijiayun.liveuibase.widgets.courseware.models.TabState.HomeworkFile;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.baijiayun.livecore.models.LPDocTranslateProgressModel;
import com.baijiayun.livecore.models.LPUploadDocModel;
import com.baijiayun.livecore.models.LPUploadingDocumentModel;
import com.baijiayun.livecore.models.courseware.LPCoursewareModel;
import com.baijiayun.livecore.models.courseware.LPMediaCoursewareModel;
import com.baijiayun.livecore.models.file.cloudfile.LPCloudFileModel;
import com.baijiayun.livecore.models.file.homework.LPHomeworkModel;
import com.baijiayun.livecore.models.file.homework.LPResHomeworkAllModel;
import com.baijiayun.livecore.models.file.homework.LPUploadHomeworkModel;
import com.baijiayun.livecore.utils.LPLogger;
import com.baijiayun.livecore.viewmodels.impl.LPDocListViewModel;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.base.BaseUIConstant;
import com.baijiayun.liveuibase.base.BaseUIConstant.FileUploadState;
import com.baijiayun.liveuibase.base.BaseUIConstant.HomeworkDownloadState;
import com.baijiayun.liveuibase.utils.DisplayUtils;
import com.baijiayun.liveuibase.utils.FileOptUtil;
import com.baijiayun.liveuibase.widgets.courseware.listeners.BaseCourseWareItemClickListener;
import com.baijiayun.liveuibase.widgets.courseware.models.DownloadHomeworkModel;
import com.baijiayun.liveuibase.widgets.courseware.models.TabState;
import com.baijiayun.liveuibase.widgets.courseware.models.UploadDocModel;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class BaseCourseWareFileAdapter extends RecyclerView.Adapter<BaseCourseWareFileViewHolder> {
    private TabState mTabState = DocFile;
    private List<LPCoursewareModel> mCoursewareList = new ArrayList<>();
    // 文档集合
    private List<LPCoursewareModel> docCopy = new ArrayList<>();
    //
    private List<LPCoursewareModel> mediaCoursewareCopy = new ArrayList<>();

    // 作业文件 List, 包含所有的作业
    private List<LPHomeworkModel> mHomeworkModelList = new ArrayList<>();
    // 展示为搜索结果，如果为搜索结果，则，仅展示这个 list，不展示 homeworkDocumentList
    private List<LPHomeworkModel> mHomeworkSearchRstList = new ArrayList<>();
    // 云盘文件 List
    private List<LPCloudFileModel> mCloudFileList = new ArrayList<>();
    // 云盘文件点击同步并打开按钮后，等待同步完成的列表
    private List<String> mWaitAddToPlayList = new ArrayList<>();
    // 文件上传 list
    private LinkedHashMap<String, UploadDocModel> mUploadDocQueue = new LinkedHashMap<>();
    // 这在下载中的记录列表
    private Map<String, DownloadHomeworkModel> downloadHomeworkQueue = new HashMap<>();

    // 是否处于搜索状态
    private boolean mIsOnSearching = false;
    // doc 搜索关键字
    private String docSearchKeyword = "";

    private ICourseWareViewListener courseWareViewListener;
    private BaseCourseWareContract.BaseCourseWarePresenter presenter;
    private boolean isTeacherOrAssistant;
    private Context context;

    public BaseCourseWareFileAdapter(ICourseWareViewListener courseWareViewListener,
                                     boolean isTeacherOrAssistant,
                                     Context context) {
        this.courseWareViewListener = courseWareViewListener;
        this.isTeacherOrAssistant = isTeacherOrAssistant;
        this.context = context;
    }

    public void setPresenter(BaseCourseWareContract.BaseCourseWarePresenter presenter) {
        this.presenter = presenter;
    }

    @NonNull
    @Override
    public BaseCourseWareFileViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.uibase_courseware_file_item_layout, viewGroup, false);
        return new BaseCourseWareFileViewHolder(view, isTeacherOrAssistant);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseCourseWareFileViewHolder viewHolder, int position) {
        List<Object> showList = getShowList();
        // region 复用时，重置视图
        viewHolder.resetView();
        // endregion

        if (position < showList.size()) {
            Object showItem = showList.get(position);
            if (showItem instanceof LPCoursewareModel) {
                // 已有 doc 文件
                viewHolder.initDocModel((LPCoursewareModel) showItem);
                viewHolder.setOnItemClickListener(
                        new DocItemClickListener((LPCoursewareModel)showItem));
            } else if (showItem instanceof LPHomeworkModel) {
                // 作业文件
                LPHomeworkModel homeworkModel = (LPHomeworkModel) showItem;
                viewHolder.initDocModel(homeworkModel);
                viewHolder.setOnItemClickListener(
                        new HomeworkItemClickListener(homeworkModel));
                checkAndInitDownloadQueue(homeworkModel, viewHolder);
            } else if (showItem instanceof LPCloudFileModel) {
                // 云盘文件
                LPCloudFileModel cloudFileModel = (LPCloudFileModel) showItem;
                viewHolder.initDocModel(cloudFileModel);
                viewHolder.setOnItemClickListener(new CloudItemClickListener(cloudFileModel));
            }
        } else {
            // 上传中文件
            LinkedHashMap<String, UploadDocModel> uploadQueue = getUploadQueue();
            UploadDocModel[] uploadDocModels = new UploadDocModel[uploadQueue.size()];
            uploadQueue.values().toArray(uploadDocModels);
            UploadDocModel uploadDocModel = uploadDocModels[position - showList.size()];
            viewHolder.initDocModel(uploadDocModel);
            viewHolder.setOnItemClickListener(new UploadItemClickListener(uploadDocModel));
        }
    }

    @Override
    public int getItemCount() {
        return mIsOnSearching ? getShowList().size() : getShowList().size() + getUploadQueue().size();
    }

    /**
     * 获取当前显示列表
     */
    @NotNull
    private List<Object> getShowList() {
        List<Object> showList = new ArrayList<>();
        switch (mTabState) {
            case DocFile:
                if (mIsOnSearching) {
                    // doc 搜索
                    for (LPCoursewareModel coursewareModel : mCoursewareList) {
                        if (coursewareModel.name.contains(docSearchKeyword)) {
                            showList.add(coursewareModel);
                        }
                    }
                } else {
                    showList.addAll(mCoursewareList);
                }
                break;
            case HomeworkFile:
                if (mIsOnSearching) {
                    // 作业搜索
                    showList.addAll(mHomeworkSearchRstList);
                } else {
                    showList.addAll(mHomeworkModelList);
                }
                break;
            case CloudFile:
                showList.addAll(mCloudFileList);
                break;
            default:
                break;
        }
        return showList;
    }

    /**
     * 获取当前显示的上传列表
     */
    private LinkedHashMap<String, UploadDocModel> getUploadQueue() {
        LinkedHashMap<String, UploadDocModel> showUploadMap = new LinkedHashMap<>();
        for (Map.Entry<String, UploadDocModel> entry : mUploadDocQueue.entrySet()) {
            boolean isHomeWorkUpload = mTabState == HomeworkFile && entry.getValue().isHomeWork();
            boolean isCloudFileUpload = mTabState == CloudFile && entry.getValue().isCloudFile();
            boolean isLocalFileUpload = mTabState == DocFile && !entry.getValue().isHomeWork() && !entry.getValue().isCloudFile();
            if (isHomeWorkUpload || isLocalFileUpload || isCloudFileUpload) {
                showUploadMap.put(entry.getKey(), entry.getValue());
            } else {
                // uploadDocModel 已没有视图，设置为 null，避免无效引用
                entry.getValue().setItemView(null);
            }
        }
        return showUploadMap;
    }

    /**
     * 根据请求的 tab 状态刷新视图
     * @param reqTab 传 null 则强制刷新
     */
    public void notifyDataWithTab(TabState reqTab) {
        if (reqTab == mTabState || reqTab == null) {
            notifyDataSetChanged();
        }
    }

    /**
     * 文档更新时，刷新所有文档 list
     */
    public void updateAllDocList(List<LPDocListViewModel.DocModel> allDocList) {
        List<LPDocListViewModel.DocModel> tmpList = new ArrayList<>(allDocList);
        docCopy.clear();
        for (LPDocListViewModel.DocModel docModel : tmpList) {
            if (!"0".equals(docModel.docId) && !docCopy.contains(docModel)) {
                docCopy.add(docModel);
                checkSyncList(docModel);
            }
        }
        sortCourseware();
        notifyDataWithTab(null);
    }

    /**
     * 更新媒体课件
     * @param mediaCoursewareModelList
     */
    public void updateMediaCoursewareList(List<LPMediaCoursewareModel> mediaCoursewareModelList) {
        mediaCoursewareCopy.clear();
        mediaCoursewareCopy.addAll(mediaCoursewareModelList);
        sortCourseware();
        notifyDataWithTab(null);
    }

    // 后台关联音视频文件 > 后台关联课件 > 教室内上传音视频 > 教室内上传课件
    private void sortCourseware() {
        mCoursewareList.clear();
        Collections.sort(mediaCoursewareCopy, (o1, o2) -> o1.lastModified - o2.lastModified);
        Collections.sort(docCopy, (o1, o2) -> o1.lastModified - o2.lastModified);
        for (LPCoursewareModel coursewareModel : mediaCoursewareCopy) {
            if (coursewareModel.bindSource == 1) {
                mCoursewareList.add(coursewareModel);
            }
        }
        for (LPCoursewareModel coursewareModel : docCopy) {
            if (coursewareModel.bindSource == 1) {
                mCoursewareList.add(coursewareModel);
            }
        }
        for (LPCoursewareModel coursewareModel : mediaCoursewareCopy) {
            if (coursewareModel.bindSource == 0) {
                mCoursewareList.add(coursewareModel);
            }
        }
        for (LPCoursewareModel coursewareModel : docCopy) {
            if (coursewareModel.bindSource == 0) {
                mCoursewareList.add(coursewareModel);
            }
        }
    }

    /**
     * 检查 等待 sync 队列
     * @param docModel 当前 docModelList 中的 docModel
     */
    private void checkSyncList(LPDocListViewModel.DocModel docModel) {
        if (mWaitAddToPlayList.size() == 0) {
            return;
        }
        for (String fileId : mWaitAddToPlayList) {
            if (fileId.equals(docModel.docId)) {
                playCourseware(docModel);
                mWaitAddToPlayList.remove(fileId);
                break;
            }
        }
    }

    // region 作业相关

    /**
     * 刷新所有作业
     */
    public void updateAllHomework(LPResHomeworkAllModel homeworkAll) {
        List<String> homeworkIds = new ArrayList<>();
        mHomeworkModelList.clear();

        for (LPHomeworkModel model : homeworkAll.getHomeworkModelList()) {
            if (!homeworkIds.contains(model.getHomeworkId())) {
                homeworkIds.add(model.getHomeworkId());
                mHomeworkModelList.add(model);
            }
        }
        notifyDataWithTab(HomeworkFile);
    }

    /**
     * 更新当前作业下载进度
     * @param homeworkId 作业id
     * @param downloadState 当前下载状态
     * @param progress 下载进度
     */
    public void updateDownloadState(String homeworkId, HomeworkDownloadState downloadState, float progress) {
        DownloadHomeworkModel downloadHomeworkModel = downloadHomeworkQueue.get(homeworkId);
        if (downloadHomeworkModel != null) {
            downloadHomeworkModel.setProgress(progress);
            downloadHomeworkModel.setDownloadState(downloadState);

            if (downloadHomeworkModel.getItemView() != null) {
                downloadHomeworkModel.getItemView().updateDownloadProgress(progress);
                if (downloadState == HomeworkDownloadState.HasDownload) {
                    // 下载成功或失败，通知 itemView 更新文件状态
                    downloadHomeworkModel.getItemView().checkHomeworkFile(
                            downloadHomeworkModel.getHomeworkModel());
                } else if (downloadState == HomeworkDownloadState.DownloadFailed) {
                    // 下载失败，显示下载失败视图
                    downloadHomeworkModel.getItemView().showDownLoadFailed();
                }
            }
        }
    }

    /**
     * 取消下载
     */
    public void cancelDownload(String homeworkId) {
        DownloadHomeworkModel downloadHomeworkModel = downloadHomeworkQueue.get(homeworkId);
        if (downloadHomeworkModel != null) {
            downloadHomeworkModel.setProgress(0);
            downloadHomeworkModel.setDownloadState(HomeworkDownloadState.NotExit);

            if (downloadHomeworkModel.getItemView() != null) {
                downloadHomeworkModel.getItemView().updateDownloadProgress(0);
            }
        }
    }

    private void checkAndInitDownloadQueue(LPHomeworkModel homeworkModel, BaseCourseWareFileViewHolder viewHolder) {
        DownloadHomeworkModel downloadHomeworkModel = downloadHomeworkQueue.get(homeworkModel.getHomeworkId());
        // 初始化时 调用 checkHomeworkFile 检查文件状态
        File file = viewHolder.checkHomeworkFile(homeworkModel);
        HomeworkDownloadState downloadState = viewHolder.getHomeworkDownloadState();
        if (downloadHomeworkModel == null) {
            // 未添加过，添加
            DownloadHomeworkModel model = new DownloadHomeworkModel(
                    homeworkModel,
                    viewHolder);
            model.setDownloadState(downloadState);
            if (downloadState == HomeworkDownloadState.Downloading && file != null) {
                // 下载中，表示为之前遗留的下载任务，那么应删除此文件，并重新设置状态
                boolean deleteRst = file.delete();
                if (deleteRst) {
                    LPLogger.d("lzdTest", "删除了遗留的下载任务文件");
                    // 移除遗留任务文件后，重新检查文件状态，更新视图
                    viewHolder.checkHomeworkFile(homeworkModel);
                }
                model.setDownloadState(HomeworkDownloadState.DownloadFailed);
            }
            downloadHomeworkQueue.put(homeworkModel.getHomeworkId(), model);
        } else {
            // 添加过，读取之前下载进度
            if (downloadState == HomeworkDownloadState.Downloading) {
                viewHolder.updateDownloadProgress(downloadHomeworkModel.getProgress());
            } else if (downloadState == HomeworkDownloadState.DownloadFailed) {
                viewHolder.showDownLoadFailed();
            }
            // 更新 itemView
            downloadHomeworkModel.setItemView(viewHolder);
        }
        viewHolder.setDownloadHomeworkModel(downloadHomeworkModel);
    }
    // endregion

    // region 搜索
    public void setOnSearching(boolean onSearching) {
        if (mIsOnSearching != onSearching) {
            mIsOnSearching = onSearching;
            notifyDataWithTab(null);
        }
    }

    public void updateDocSearchKeyword(String keyword) {
        docSearchKeyword = keyword;
        notifyDataWithTab(null);
    }

    /**
     * 刷新作业搜索结果
     */
    public void updateHomeworkSearchRst(LPResHomeworkAllModel searchRst) {
        List<String> homeworkIds = new ArrayList<>();
        mHomeworkSearchRstList.clear();
        if (searchRst == null) {
            notifyDataWithTab(HomeworkFile);
            return;
        }

        for (LPHomeworkModel model : searchRst.getHomeworkModelList()) {
            if (!homeworkIds.contains(model.getHomeworkId())) {
                homeworkIds.add(model.getHomeworkId());
                mHomeworkSearchRstList.add(model);
            }
        }
        notifyDataWithTab(HomeworkFile);
    }

    // endregion

    // region 云盘相关

    /**
     * 更新云盘 list
     */
    public void updateAllCloudFile(List<LPCloudFileModel> allCloudFile) {
        mCloudFileList = new ArrayList<>(allCloudFile);
        notifyDataWithTab(CloudFile);
    }
    // endregion

    // region 上传相关

    /**
     * 更新文件上传状态
     */
    public void updateUploadState(LPUploadingDocumentModel uploadingDocModel, FileUploadState newState,
                                  LPDocTranslateProgressModel progressModel) {
        UploadDocModel model = mUploadDocQueue.get(uploadingDocModel.getFilePath());
        if (model != null) {
            if (newState == model.getNowState()) {
                // 当前状态与新状态一致，不做无意义的刷新
                return;
            }
            // region 上传中，转码中，保存中间数据，供中途取消使用
            model.setFileId(uploadingDocModel.getFileId());
            model.setHomeworkId(uploadingDocModel.getHomeworkId());
            // endregion
            model.setNowState(newState);
            if (model.getItemView() != null) {
                model.getItemView().setFileState(model.getNowState());
            }
            if (progressModel != null) {
                model.setErrorModel(progressModel);
            }
            if (model.isHomeWork()) {
                notifyDataWithTab(HomeworkFile);
            } else if (model.isCloudFile()) {
                notifyDataWithTab(CloudFile);
            } else {
                notifyDataWithTab(DocFile);
            }
        }
    }

    /**
     * 增加上传文件
     */
    public void addUploadModel(LPUploadingDocumentModel model) {
        if (model.isHomework()) {
            mUploadDocQueue.put(model.getFilePath(), new UploadDocModel(model.getFilePath(),
                    true, false));
            notifyDataWithTab(HomeworkFile);
        } else if (model.isCloudFile()) {
            mUploadDocQueue.put(model.getFilePath(), new UploadDocModel(model.getFilePath(),
                    false, model.isAnimPPT(), true));
            notifyDataWithTab(CloudFile);
        } else {
            mUploadDocQueue.put(model.getFilePath(), new UploadDocModel(model.getFilePath(), model.isAnimPPT()));
            notifyDataWithTab(DocFile);
        }
    }

    /**
     * 移除上传 item
     */
    public void removeUpload(String path) {
        UploadDocModel docModel = mUploadDocQueue.remove(path);
        if (docModel == null) {
            return;
        }
        if (docModel.isHomeWork()){
            notifyDataWithTab(HomeworkFile);
        } else if (docModel.isCloudFile()) {
            notifyDataWithTab(CloudFile);
        } else {
            notifyDataWithTab(DocFile);
        }
    }
    // endregion

    // region 视图变更
    public void updateTabState(TabState tabState) {
        if (mTabState != tabState) {
            mTabState = tabState;
            notifyDataSetChanged();
        }
    }

    /**
     * 断网
     */
    public void onRoomLoseConnect() {
        // 上传中 item 展示为上传失败
        for (UploadDocModel docModel : mUploadDocQueue.values()) {
            if (docModel.getNowState() == FileUploadState.Uploading) {
                docModel.setNowState(FileUploadState.UploadFailed);
                LPDocTranslateProgressModel errorModel =
                        new LPDocTranslateProgressModel(BaseUIConstant.ERROR_CODE_UPLOAD_FAIL_CANT_REUPLOAD_CUSTOM_CODE
                                , context.getString(R.string.base_course_manage_upload_fail_please_reupload));
                docModel.setErrorModel(errorModel);
            }
        }
    }
    // endregion

    // region item 点击事件回调

    /**
     * 文档 item 点击事件回调
     */
    class DocItemClickListener extends BaseCourseWareItemClickListener implements BaseCourseWareFileViewHolder.IOnDocItemClickListener {
        LPCoursewareModel coursewareModel;

        public DocItemClickListener(LPCoursewareModel coursewareModel) {
            this.coursewareModel = coursewareModel;
        }

        @Override
        public void onPlay() {
            if(coursewareModel.coursewareType == LPCoursewareModel.LPCoursewareType.DOC) {
                int checkCanPlayRst = checkCanPlay(coursewareModel.ext);
                if (checkCanPlayRst != SUPPORT_FLAG) {
                    courseWareViewListener.onReminderMsg(context.getString(checkCanPlayRst));
                    return;
                }
            }
            playCourseware(coursewareModel);
        }

        @Override
        public void onDelete(String fileId) {
            if (courseWareViewListener != null) {
                if(coursewareModel.coursewareType == LPCoursewareModel.LPCoursewareType.DOC) {
                    courseWareViewListener.onDeleteDoc(((LPDocListViewModel.DocModel)coursewareModel).docId, false);
                } else {
                    courseWareViewListener.onDeleteMediaCourseware(coursewareModel.number);
                }
            }
        }
    }

    /**
     * 云盘文件 item 点击事件回调
     */
    class CloudItemClickListener extends BaseCourseWareItemClickListener implements BaseCourseWareFileViewHolder.IOnCloudItemClickListener {
        LPCloudFileModel cloudFileModel;

        public CloudItemClickListener(LPCloudFileModel cloudFileModel) {
            this.cloudFileModel = cloudFileModel;
        }

        @Override
        public void onPlay() {
            if (cloudFileModel.isDirectory()) {
                return;
            }
            int checkCanPlayRst = checkCanPlay(cloudFileModel.getFExt());
            if (checkCanPlayRst != SUPPORT_FLAG) {
                if(cloudFileModel.videoInfo != null) {
                    presenter.playMediaCourseware(new LPMediaCoursewareModel(cloudFileModel));
                } else {
                    courseWareViewListener.onReminderMsg(context.getString(checkCanPlayRst));
                }
                return;
            }
            // 文档要转码同步到教室课件中，媒体课件不用
            if (mWaitAddToPlayList.contains(cloudFileModel.getFileId()) || presenter == null) {
                // 已经在等待同步队列了
                return;
            }
            // 未同步，或未记录同步信息，需要请求一次转码信息，再匹配 docId，如果已经 docAdd 过，则直接播放，否则 docAdd
            presenter.requestFileTransfer(cloudFileModel, new BaseCourseWareContract.IOnRequestTransferListener() {
                @Override
                public void onSuccess(LPDocListViewModel.DocModel docModel) {
                    // 获取转码进度成功，已 doc add
                    playCourseware(docModel);
                    notifyDataWithTab(CloudFile);
                }

                @Override
                public void onWaitForDocAdd() {
                    // 加入等待队列，在 doc list 变更时，检查
                    mWaitAddToPlayList.add(cloudFileModel.getFileId());
                }
            });
        }

        @Override
        public void onDelete(String id) {
            courseWareViewListener.onDeleteCloudFile(cloudFileModel);
        }

        @Override
        public void onClickDirectory() {
            if (!cloudFileModel.isDirectory()) {
                return;
            }
            presenter.requestCloudFileInDir(cloudFileModel);
        }
    }

    /**
     * 上传 item 点击监听
     */
    class UploadItemClickListener implements BaseCourseWareFileViewHolder.IOnUploadItemClickListener {
        private UploadDocModel uploadDocModel;

        public UploadItemClickListener(UploadDocModel uploadDocModel) {
            this.uploadDocModel = uploadDocModel;
        }

        @Override
        public void onPlay() {
            // do nothing
        }

        @Override
        public void onDelete(String fileId) {
            removeUpload(uploadDocModel.getPath());
        }

        @Override
        public void onUploadByNormal() {
            // 动态失败切普通上传， 不用删除原 id 文件，直接以静态方式上传即可
            if (presenter != null) {
                presenter.sendPPTDocument(uploadDocModel.getPath(), false);
            }
        }

        @Override
        public void onReUpload(String fileId) {
            // 以原本方式重新上传，需要先删除原 id 文件，再开始重新上传
            if (courseWareViewListener != null) {
                courseWareViewListener.onDeleteDoc(fileId, true);
            }
            if (presenter != null) {
                presenter.sendPPTDocument(uploadDocModel.getPath(), uploadDocModel.isAnim());
            }
        }

        @Override
        public void onCancelUpload() {
            // 取消上传
            removeUpload(uploadDocModel.getPath());
            courseWareViewListener.onReminderMsg(context.getString(R.string.base_course_manage_cancel_upload));
            presenter.cancelUpload(uploadDocModel.getPath());
        }

        @Override
        public void onCancelTransfer() {
            courseWareViewListener.onCancelTransfer(uploadDocModel);
        }
    }

    /**
     * 作业 item 点击监听
     */
    class HomeworkItemClickListener extends BaseCourseWareItemClickListener implements BaseCourseWareFileViewHolder.IOnHomeworkItemClickListener {
        private LPHomeworkModel homeworkModel;

        public HomeworkItemClickListener(LPHomeworkModel homeworkModel) {
            this.homeworkModel = homeworkModel;
        }

        @Override
        public void onPlay() {
            int checkCanPlayRst = checkCanPlay(homeworkModel.getFext());
            if (checkCanPlayRst != SUPPORT_FLAG) {
                courseWareViewListener.onReminderMsg(context.getString(checkCanPlayRst));
                return;
            }
            if (!homeworkModel.isCanPreview() || mWaitAddToPlayList.contains(homeworkModel.getFid()) || presenter == null) {
                // 不可播放 或 已在等待队列
                return;
            }
            // 未同步，或未记录同步信息，需要请求一次转码信息，再匹配 docId，如果已经 docAdd 过，则直接播放，否则 docAdd
            presenter.requestFileTransfer(LPUploadHomeworkModel.copyData(homeworkModel), new BaseCourseWareContract.IOnRequestTransferListener() {
                @Override
                public void onSuccess(LPDocListViewModel.DocModel docModel) {
                    playCourseware(docModel);
                    notifyDataWithTab(HomeworkFile);
                }

                @Override
                public void onWaitForDocAdd() {
                    // 加入等待队列，在 doc list 变更时，检查
                    mWaitAddToPlayList.add(homeworkModel.getFid());
                }
            });

        }

        @Override
        public void onDelete(String homeworkId) {
            if (TextUtils.isEmpty(homeworkId)) {
                return;
            }
            courseWareViewListener.onDeleteHomework(homeworkId);
        }

        @Override
        public void onDownload(File file) {
            if (presenter != null) {
                presenter.downloadHomework(homeworkModel, file);
            }
        }

        @Override
        public void onCancelDownload(File file) {
            if (presenter != null) {
                presenter.cancelDownloadHomework(file);
            }
        }
    }

    /**
     * 播放课件
     */
    private void playCourseware(LPCoursewareModel coursewareModel) {
        // bds文件
        if (coursewareModel.ext != null && coursewareModel.ext.endsWith(".bds") && presenter != null) {
            LPDocListViewModel.DocModel docModel = (LPDocListViewModel.DocModel) coursewareModel;
            presenter.playBds(docModel);
            return;
        }
        //普通课件
        if(coursewareModel.coursewareType == LPCoursewareModel.LPCoursewareType.DOC) {
            LPDocListViewModel.DocModel docModel = (LPDocListViewModel.DocModel) coursewareModel;
            if (FileOptUtil.isImageFile(docModel.ext) && !presenter.enableImageShowAsDoc()) {
                // 播放图片
                LPUploadDocModel lpUploadDocModel = new LPUploadDocModel();
                if (docModel.width != 0) {
                    lpUploadDocModel.width = (int) docModel.width;
                    lpUploadDocModel.height = (int) docModel.height;
                } else {
                    int _100dp = DisplayUtils.dip2px(context, 100);
                    lpUploadDocModel.width = _100dp;
                    lpUploadDocModel.height = _100dp;
                }
                lpUploadDocModel.url = docModel.url;
                try {
                    lpUploadDocModel.fileId = Long.parseLong(docModel.docId);
                } catch (NumberFormatException e) {
                    lpUploadDocModel.fileId = 0L;
                    e.printStackTrace();
                }
                if (courseWareViewListener != null) {
                    courseWareViewListener.onPlayImg(lpUploadDocModel);
                }
            } else {
                // 播放课件
                if (presenter == null || !presenter.playDoc(docModel)) {
                    return;
                }
            }
            if (courseWareViewListener != null) {
                courseWareViewListener.onReminderMsg(context.getString(R.string.base_course_manage_has_open_doc));
            }
        } else {
            //音视频课件
            presenter.playMediaCourseware((LPMediaCoursewareModel) coursewareModel);
        }
    }
    // endregion

    public void destroy() {
        mCoursewareList.clear();
        mHomeworkModelList.clear();
        mHomeworkSearchRstList.clear();
        mUploadDocQueue.clear();
        downloadHomeworkQueue.clear();
        mIsOnSearching = false;
        docSearchKeyword = "";
        mWaitAddToPlayList.clear();
        presenter = null;
    }
}
